<template>
  <div>
    <a-spin size="large" :spinning="spinning">
      <div class="leftBox">
        <FormOperation :isEdit="true" :btnList="btnList"></FormOperation>
      </div>
      <div class="rightBox">
        <a-row class="titleRowBox">
          <div style="width: 12%" :span="3">文字</div>
          <div style="width: 13%" :span="4">样式</div>
          <div style="width: 12.5%" :span="4">图标</div>
          <div style="width: 25%" :span="4">调用服务</div>
          <div style="width: 17%" :span="4">流程变量</div>
          <a-button
            v-if="spinning == false"
            :style="{ marginRight: '8px' }"
            type="primary"
            size="small"
            icon="plus"
            @click="modelShow(true)"
          >
            添加
          </a-button>
          <a-button type="primary" size="small" icon="copy" @click="copyBtn()"> 复制 </a-button>
          <a-col :span="1"></a-col>
        </a-row>
        <!-- 内容 -->
        <div class="gundongBox">
          <draggable
            style="width: 99%"
            :group="{ name: 'relationTable' }"
            v-model="btnList"
            v-bind="dragOptions"
            @start="drag = true"
            @end="
              drag = false
              btnShow = true
            "
          >
            <span @click="editItemBtn(item, index)" class="cardBox" v-for="(item, index) in btnList" :key="item.key">
              <a-row style="width: 100%; padding-left: 20px">
                <a-col :span="3">
                  {{ item.text_ }}
                </a-col>
                <a-col :span="3">
                  {{ item.class_ }}
                </a-col>
                <a-col :span="3">
                  {{ item.icon_ }}
                </a-col>
                <a-col :span="7">
                  {{
                    item.postexecutors && item.postexecutors.length > 30
                      ? item.postexecutors.substring(0, 30) + '...'
                      : item.postexecutors
                  }}
                </a-col>
                <a-col :span="4">
                  {{
                    item.variable && item.variable.length > 15 ? item.variable.substring(0, 15) + '...' : item.variable
                  }}
                </a-col>
                <a-col class="closeBox" @click.stop="delCol(index, item)" :span="1"
                  ><div><a-icon type="close" /></div
                ></a-col>
              </a-row>
            </span>
          </draggable>
        </div>
      </div>
    </a-spin>

    <!-- 弹出层 -->
    <a-modal width="40%" v-model="isModel" title="添加按钮" :footer="null" :forceRender="true">
      <a-form-model ref="btnFormRef" :rules="rules" :model="btnForm">
        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="文字" prop="text_">
          <a-input v-model="btnForm.text_" :maxLength="10" />
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="样式" prop="class_">
          <a-input v-model="btnForm.class_" style="width: 100px; margin-right: 20px" placeholder="请选择样式" />
          选择器：<colorPicker @change="colorChange" :value="btnForm.class_" />
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="图标" prop="icon_">
          <a-input v-model="btnForm.icon_" @change="iconAdd" @click="iconAdd" addon-before="选择图标">
            <a-icon slot="addonAfter" :type="btnForm.icon_" />
          </a-input>
          <a-popover trigger="click" placement="bottomRight" v-model="visible">
            <template slot="title">
              <a-input-search v-model="searchValue" placeholder="输入英文关键词进行搜索" @change="filterIcon" />
            </template>

            <template slot="content">
              <div class="icon-box">
                <div
                  v-for="(item, index) in iconArr"
                  :key="item + index"
                  @click="handleClick(item)"
                  class="icon-content"
                >
                  <a-icon :type="item" style="font-size: 18px" />
                  <!-- <component :is="$antIcons[item]" /> -->
                </div>
              </div>
            </template>
            <slot name="iconSelect"></slot>
          </a-popover>
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="点击事件">
          <a-row>
            <a-col :span="12"><a-input v-model="btnForm.click_" :maxLength="1000" /></a-col>
            <a-col :span="12">
              <a-select v-model="btnForm.click_" :maxLength="1000">
                <a-select-option v-for="item in btnTypeList" :key="item.value" :value="item.value">
                  {{item.name}}
                </a-select-option>
              </a-select>
            </a-col>
          </a-row>
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="调用任务">
          <a-input v-model="btnForm.postexecutors" :maxLength="1000" />
          <div v-if="isModel">
            <postexecutorView :postexecutors="btnForm.postexecutors" @changePostextcutor="(postexecutors)=>postexecutorsEdit(postexecutors)"></postexecutorView>
          </div>
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="流程变量">
          <a-input v-model="btnForm.variable" :maxLength="1000" placeholder="Object({对象名: 对象值})" />
          <variable-view v-if="isModel" :variable="btnForm.variable" @changeVariable="(newvisible)=>variableEdit(newvisible)">
          </variable-view>
        </a-form-model-item>

        <a-form-model-item :label-col="labelCol" :wrapper-col="wrapperCol" label="提示消息">
          <a-textarea v-model="btnForm.message" :maxLength="1000" placeholder="if(条件表达式) {提示内容字符串}" />
        </a-form-model-item>
      </a-form-model>

      <div style="text-align: center">
        <a-button type="primary" @click="dtnSave"> 添加 </a-button>
      </div>
    </a-modal>

    <!-- 按钮复制弹框组件 -->
    <NODEBTNCOPY
      ref="btnCopyRef"
      @f_copySave="s_copySave"
      :formid="this.$route.params.formid"
      :stepid="this.$route.params.stepid"
    />
  </div>
</template>
<script>
import FormOperation from '@/views/workflow/Wf_FormOperation.vue'
import { Tp_operation } from '@/enumeration/Tp_operation.js'
import iconPicker from '@/components/k-form-design/packages/KFormDesign/module/formItemProperties.vue'
import VueIcon from '@ant-design/icons-vue'
import { stepbtnBatchSave, queryAct_dsn_form_stepbtnList } from '@/api/workflow/act_dsn_form_stepbtn.js'
import draggable from 'vuedraggable'
import { WF_NodeBtnClickType } from '@/enumeration/Wf_NodeBtn'
import postexecutorView from '@/views/workflow/Wf_NodeBtnPostexecutor.vue'
import  variableView from '@/views/workflow/Wf_NodeBtnVariable.vue'
// import { save } from '@/api/workflow/act_dsn_btn.js'
const icons = VueIcon.definitions.collection
export default {
  data() {
    return {
      btnShow: false,
      drag: false,
      spinning: true, // false
      queryParam: {
        pageSize: 2147483647,
        f_formid_: this.$route.params.formid,
        f_stepid_: this.$route.params.stepid,
        sort: 'indexsort',
        order: 'ASC',
      },
      btnList: [], // 配置的按钮列表
      Tp_operation: Tp_operation, // 环节按钮参数所做操作枚举
      visible: false,
      iconArr: [],
      searchValue: '',
      theme: 'outline',
      iconarr: [],
      btnForm: {
        formid_: null, // 引用表单id
        stepid_: null, // 环节id
        text_: null, // 按钮文字
        class_: '#1491ff', // 按钮样式
        icon_: null, // 按钮图标
        click_: 'passRecord()', // 点击事件
        postexecutors: null, // 环节完成后调用任务Json(数组)
        variable: null, // 流程变量
        message: null, // 提示消息
      },
      isModel: false, // 弹出层状态控制
      spinning: false, // 加载状态
      labelCol: { span: 4 }, // label宽
      wrapperCol: { span: 20 }, // 组件宽
      btnTypeList: WF_NodeBtnClickType, //按钮点击事件类型
      rules: {
        text_: [
          {
            required: true,
            message: '请输入按钮文字',
            pattern: '[^\\s\\r\\n]',
          },
        ],
        class_: [
          {
            required: true,
            message: '请选择按钮样式',
          },
        ],
        icon_: [
          {
            required: true,
            message: '请选择按钮图标',
          },
        ],
      },
    }
  },
  async created() {
    this.getBtnList()
  },
  computed: {
    dragOptions() {
      return {
        animation: 200,
        group: 'description',
        disabled: false,
        ghostClass: 'ghost',
      }
    },
  },
  mounted() {
    this.iconarr = Object.values(icons)
      .filter((t) => t.theme == this.theme)
      .map((i) => i.name)
    this.iconArr = this.iconarr
  },
  watch: {
    visible(val, old) {
      this.searchValue = ''
      this.iconArr = this.iconarr
    },
  },
  methods: {
    // 子组件调用复制按钮配置
    s_copySave(list) {
      list.forEach((v) => {
        v.stepid_ = this.$route.params.stepid
        v.formid_ = this.$route.params.formid
        delete v['id']
        delete v['primaryKey']
      })
      this.btnList = list
    },
    // 按钮复制
    copyBtn() {
      this.$refs.btnCopyRef.f_init()
    },
    // 按钮颜色变更回调
    colorChange(value) {
      this.btnForm.class_ = value
      // console.log('value', value, this.btnForm)
    },
    // 编辑功能
    editItemBtn(item, index) {
      this.btnForm = { ...item, index }
      // 存一个下标, 如果保存把之前的删除掉
      // console.log('编辑', this.btnForm)
      this.isModel = true
    },
    // 获取按钮列表
    getBtnList() {
      this.spinning = true
      queryAct_dsn_form_stepbtnList(this.queryParam)
        .then((res) => {
          console.log('按钮配置列表', res)
          if (res.code == 0) {
            this.btnList = res.data.records || []
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 按钮保存
    stepbtnSave(status) {
      this.btnList.forEach((v, i) => {
        v.indexsort = i
      })
      // console.log('this.btnList', this.btnList)
      this.spinning = true
      stepbtnBatchSave(this.$route.params.formid, this.$route.params.stepid, this.btnList)
        .then((res) => {
          if (res.code == 0) {
            this.$message.success('保存成功')
            if (status) {
              setTimeout(() => {
                this.$emit('handleBack')
              }, 1000)
            }
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    // 删除一项配置
    delCol(index, item) {
      this.btnList.splice(index, 1)
    },
    // 按钮样式chonge
    radioClass(e) {
      console.log('按钮样式', e.target.value)
      if (['check', 'exclamation', 'close', null].includes(this.btnForm.icon_)) {
        if (e.target.value == 'primary') {
          this.btnForm.icon_ = 'check'
        } else if (e.target.value == 'warning') {
          this.btnForm.icon_ = 'exclamation'
        } else if (e.target.value == 'danger') {
          this.btnForm.icon_ = 'close'
        }
      }
    },
    // 新增图标
    dtnSave() {
      this.$refs.btnFormRef.validate((valid) => {
        if (valid) {
          let item = {}
          for (let key in this.btnForm) {
            item[key] = this.btnForm[key]
          }
          item.formid_ = this.$route.params.formid
          item.stepid_ = this.$route.params.stepid
          item.key = Date.now().toString(36)
          // 如果是编辑进来的, 删除之前那个
          if (this.btnForm.index != undefined && this.btnForm.index != null) {
            this.btnList.splice(this.btnForm.index, 1, item)
          } else {
            this.btnList.push(item)
          }
          console.log('item', item)
          this.isModel = false
        }
      })
      // console.log('新增按钮', this.btnList)
    },
    // 图标添加弹框
    iconAdd() {
      this.visible = true
    },
    // 弹出层控制
    modelShow(show) {
      // 回显配置
      for (let key in this.btnForm) {
        this.btnForm[key] = null
      }
      this.btnForm.click_ = 'passRecord()'
      this.btnForm.class_ = '#1491ff'
      this.isModel = show
    },
    handleClick(icon) {
      this.btnForm.icon_ = icon
      this.$refs.btnFormRef.validateField('icon_')
      this.visible = false
    },
    filterIcon() {
      if (this.searchValue) {
        this.iconArr = this.iconarr.filter((item) => item.toLowerCase().includes(this.searchValue.toLowerCase()))
      } else {
        this.iconArr = this.iconarr
      }
    },
    postexecutorsEdit(postexecutors){
      if(postexecutors === '[]'){
        postexecutors = null
      }
      this.btnForm.postexecutors = ''
      this.btnForm.postexecutors = postexecutors
    },
    variableEdit(newvisible){
      if(newvisible !== 'Object({})'){
        this.btnForm.variable = ''
        this.btnForm.variable = newvisible
      }else {
        this.btnForm.variable = ''
      }
    },
  },
  components: {
    FormOperation,
    iconPicker,
    draggable,
    NODEBTNCOPY: () => import('@/views/workflow/Wf_NodeBtnCopy.vue'),
    postexecutorView,
    variableView
  },
}
</script>

<style scoped>
.closeBox {
  color: red;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 2px;
}
.titleRowBox {
  display: flex;
  align-items: center;
  height: 50px;
  border-bottom: 1px solid #ccc;
  padding-left: 2.5%;
}
.leftBox,
.rightBox {
  height: 72vh;
  width: 49%;
  float: left;
  zoom: 1;
  border: 1px solid #e8e8e8;
}
.leftBox {
  padding: 10px;
  margin-right: 2%;
}
.icon-box {
  overflow: auto;
  font-size: 20px;
  width: 250px;
  height: 230px;
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  align-content: flex-start;
  justify-content: center;
}

.icon-content {
  width: 45px;
  height: 40px;
  margin: 5px;
  cursor: pointer;
  text-align: center;
  border-radius: 6px;
  border: 1px solid #ccc;
}
.icon-content:hover {
  background: #1890ff;
}
.gundongBox {
  height: 65vh;
  overflow: auto;
  position: relative;
  /* border: 1px solid blue; */
}
.cardBox {
  height: 50px;
  width: 100%;
  background-color: white;
  box-shadow: 0 2px 4px 0 #ccc;
  border-radius: 5px;
  display: inline-block;
  vertical-align: top;
  margin-top: 4px;
  display: flex;
  align-items: center;
}
</style>